package com.sjh;

/**
 * @author jack
 * @data 2020/8/21 6:55 下午
 */
public class TraditionalThreadCommunication {
    //子线程循环10次和主线程循环100次， 两者交替运行50次
    public static void main(String[] args) {
        Business business = new Business();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 50; i++) {
                    business.sub(i);
                }
            }
        },"sub").start();

        for (int i = 1; i <= 50; i++) {
            business.main(i);
        }


    }
    static class Business {
        private boolean isShouldMain = true;
        public synchronized void main(int num) {

            while (isShouldMain) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //循环100次
            for (int i = 1; i <= 100; i++) {
                System.out.println(String.format("main execute of: %s loop of:%s ", i, num));
            }
            isShouldMain = true;
            this.notify();
        }

        public synchronized void sub(int num) {
            while (!isShouldMain) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //循环10次
            for (int i = 1; i <= 10; i++) {
                System.out.println(String.format(Thread.currentThread().getName() + " execute of: %s loop of:%s ", i, num));
            }
            isShouldMain = false;
            this.notify();

        }
    }
}

